﻿#ifndef __SS_SINGLETON_H__
#define __SS_SINGLETON_H__
#include "./thread/threadLock/ssAtomicLock.h"

namespace StarSeeker
{

template<class T>
class ssSingle
{
private:
	ssSingle();
	ssSingle(const ssSingle&);
	ssSingle& operator = (const ssSingle&);
	static T* s_instance;
	static ssAtomicLock s_lock;
public:
	inline static void create_instance()
	{
		s_lock.Lock();
		if (!s_instance)
		{
			s_instance = new T;
		}
		s_lock.Unlock();
	}

	inline static T* instance()
	{
		if (!s_instance)
		{
			create_instance();
		}
		return s_instance;
	}

	inline static void delete_instance()
	{
		s_lock.Lock();
		if (s_instance)
		{
			delete s_instance;
			s_instance = 0;
		}
		s_lock.Unlock();
	}
};

template<class T>
T* ssSingle<T>::s_instance = 0;
template<class T>
ssAtomicLock ssSingle<T>::s_lock;


//不使用模板
#define SS_SINGLETON(T) private: \
	T(const T&); \
	T& operator = (const T&); \
	static T* s_instance; \
	static ssAtomicLock s_lock;\
public:\
	inline static void create_instance()\
	{\
		s_lock.Lock();\
		if (!s_instance)\
		{\
			s_instance = new T; \
		}\
		s_lock.Unlock();\
	}\
	inline static T* instance()\
	{\
		if (!s_instance)\
		{\
			create_instance();\
		}\
		return s_instance; \
	}\
	inline static void delete_instance()\
	{\
		s_lock.Lock();\
		if (s_instance)\
		{\
			delete s_instance; \
			s_instance = 0; \
		}\
		s_lock.Unlock();\
	}

#define SS_SINGLETON_INIT(T) T* T::s_instance = 0;\
ssAtomicLock T::s_lock;

}
#endif
